package com.cn.springcloudwechat.upload;

import com.alibaba.fastjson.JSON;
import com.cn.springcloudwechat.model.cos.CosClientEntity;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Transfer;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferProgress;
import com.qcloud.cos.transfer.Upload;
import org.joda.time.DateTime;

import java.io.File;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CosUtils {
    private static String BASEPATH_URL = "http://cos-vc.cdaxkj.cn";

    /**
     * 上传文件
     *
     * @param path
     * @return
     */
    // 将本地文件上传到COS
    public static String SimpleUploadFileFromLocal(String path) {
        if (path == null || "".equals(path)) {
            return "";
        }
        // 生成cos客户端
        COSClient cosclient = CosClientEntity.getInstace();
        // bucket名需包含appid
        String bucketName = CosClientEntity.bucketName;
        String time = String.valueOf(new DateTime().getMillis());
        File localFile = new File(path);
        String dz = "";
        //图片上传地址
        if (path.indexOf(".jpg") != -1 || path.indexOf(".png") != -1) {
            dz = CosClientEntity.imgKey + time + localFile.getName();
        } else {
            //视频上传地址
            dz = CosClientEntity.movieKey + time + localFile.getName();
        }
        String key = dz;
        //创建一个线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        // 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
        TransferManager transferManager = new TransferManager(cosclient, threadPool);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        UploadResult uploadResult = null;
        try {
            Upload upload = transferManager.upload(putObjectRequest);
            //上传过程
            /*showTransferProgress(upload);*/
            // 等待传输结束（如果想同步的等待上传结束，则调用 waitForCompletion）
            //          upload.waitForCompletion();
            uploadResult = upload.waitForUploadResult();
//            // putobjectResult会返回文件的etag
//            String etag = uploadResult.getETag();
            System.out.println(JSON.toJSONString(uploadResult));
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();
        System.out.println("上传路径:" + BASEPATH_URL + File.separator + dz);
        return dz;
    }

    /**
     * 下载文件
     *
     * @param path
     */
    public static void download(String path) {
        COSClient cosClient = CosClientEntity.getInstace();
        // 指定要下载到的本地路径
        //File downFile = new File("src/test/resources/mydown.txt");
        File downFile = new File(path);
        // 指定要下载的文件所在的 bucket 和对象键
        GetObjectRequest getObjectRequest = new GetObjectRequest(CosClientEntity.bucketName, path);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
        // 关闭客户端(关闭后台线程)
        cosClient.shutdown();
    }

    /**
     * 删除文件
     */
    public static void delete(String path) {
        COSClient cosClient = CosClientEntity.getInstace();
        // 指定要删除的 bucket 和对象键
        cosClient.deleteObject(CosClientEntity.bucketName, path);
        // 关闭客户端(关闭后台线程)
        cosClient.shutdown();
    }

    //**************************************bucket操作****************//
    // 创建bucket
    public static void CreateBucket() {
        //构造cosclient对象
        COSClient cosClient = CosClientEntity.getInstace();
        ;
        //请求
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(CosClientEntity.bucketName);
        // 设置bucket的权限为PublicRead(公有读私有写), 其他可选有私有读写, 公有读私有写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        Bucket bucket = cosClient.createBucket(createBucketRequest);

        // 关闭客户端
        cosClient.shutdown();
    }

    // 删除bucket, 只用于空bucket, 含有数据的bucket需要在删除前清空删除。
    public static void DeleteBucket() {
        //构造cosclient对象
        COSClient cosClient = CosClientEntity.getInstace();
        // 删除bucket
        cosClient.deleteBucket(CosClientEntity.bucketName);

        // 关闭客户端
        cosClient.shutdown();
    }

    /**
     * 查询bucket是否存在
     */
    public static boolean bucketExist() {
        //构造cosclient对象
        COSClient cosClient = CosClientEntity.getInstace();
        // 判断bucket是否存在
        boolean flag = cosClient.doesBucketExist(CosClientEntity.bucketName);
        // 关闭客户端
        cosClient.shutdown();
        return flag;
    }


    /**
     * 文件上传
     *
     * @param file 流
     * @return
     */
    public static String SimpleUploadFileFromLocal(File file) {
        String path = file.getPath();
        if (path == null || "".equals(path)) {
            return "";
        }
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(CosClientEntity.secretId, CosClientEntity.secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(CosClientEntity.regionName));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = CosClientEntity.bucketName;
        String time = String.valueOf(new DateTime().getMillis());
        // File localFile = new File(path);
        String dz = "";
        //图片上传地址
        if (path.indexOf(".jpg") != -1 || path.indexOf(".png") != -1
                || path.indexOf(".jpeg") != -1 || path.indexOf(".gif") != -1
                || path.indexOf(".bmp") != -1
                ) {

            dz = CosClientEntity.imgKey + time + file.getName();

        } else {
            //视频上传地址
            dz = CosClientEntity.movieKey + time + file.getName();
        }
        String key = dz;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();
        return BASEPATH_URL + "/" + dz;
    }

    /**
     * 上传过程
     *
     * @param transfer
     */
    private static void showTransferProgress(Transfer transfer) {
        System.out.println(transfer.getDescription());
        do {
            TransferProgress progress = transfer.getProgress();
            long so_far = progress.getBytesTransferred();
            long total = progress.getTotalBytesToTransfer();
            double pct = progress.getPercentTransferred();
            System.out.printf("[%d / %d]  %d\n", so_far, total, pct);
        } while (transfer.isDone() == false);
        System.out.println(transfer.getState());
    }

    public static void main(String[] args) {
        String realPath = "12 (a).txt";
        realPath = realPath.trim();
        System.out.println(realPath.replace(" ", ""));
        // try {
        //  realPath= ResourceUtils.getURL("classpath:").getPath();
        //  realPath="D:/123.txt";
        //  SimpleUploadFileFromLocal("D:/Users/Administrator/AppData/Roaming/FFWallpaper/projects/defaultprojects/6/video.mp4");
        //  upload(realPath);
        //  } catch (FileNotFoundException e) {
        //       e.printStackTrace();
        //   }
    }
}
